import {
    MessageBox,
    Message,
    Loading
} from 'element-ui';
import axios from 'axios'; //没有在组件里
import router from '../router'; //路由地图
import Cookies from 'js-cookie';

// 声明实例一个永远都是pendding 状态的promise
const alwaysPendinfPromise = new Promise(() => {});


let instanLoading = null;
let loadingAjaxCount = 0; //记录当前loading开启的次数，主要解决同时发起多个 ajax，loadiing打开关闭的混乱问题

function beginAjax() {
    if (loadingAjaxCount === 0)
        instanLoading = Loading.service({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
    loadingAjaxCount++;
}

function endAjax() {
    if (loadingAjaxCount === 1) {
        instanLoading.close();
        instanLoading = null;
    }
    loadingAjaxCount--;
}
// 创建axios 实例
const instance = axios.create();
// 设置实例请求发出前的拦截器

instance.interceptors.request.use(
    config => {
        config.headers = {
            "Authorization": Cookies.get("token")
        }
        beginAjax();
        return config;
    },
    (error) => {
        endAjax();
        MessageBox.alert(
            error.message,
            "提示", {
                type: 'error',
            }
        );
        return alwaysPendinfPromise;
    }
);
// 设置实例请求返回的拦截器
instance.interceptors.response.use(
    async response => {

        // 延迟5毫秒
        await new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve();
            }, 500);
        })

        endAjax();

        if (response.status === 200) {
            let {
                status,
                data,
                message
            } = response.data;
            switch (status) {
                case 200:
                    // if (response.headers.authorization) Cookies.set("token", response.headers.authorization);

                    if (message)
                        Message({
                            message,
                            type: 'success'
                        })
                    return data;
                case 401:
                    Cookies.remove("token");
                    // router.replace({
                    //     path: '/login',
                    //     query: {
                    //         back: router.currentRoute.fullPath
                    //     }
                    // });
                    router.replace('/login');
                case 404:
                case 199:
                case 500:
                    if (message) MessageBox.alert(
                        message,
                        "提示", {
                            type: 'error',
                        }
                    );
                    return alwaysPendinfPromise;
            }
        } else {
            MessageBox.alert(
                message,
                "提示", {
                    type: 'error',
                }
            );
            return alwaysPendinfPromise;
        }
    },
    error => {
        endAjax();
        MessageBox.alert(
            error.message,
            "提示", {
                type: 'error',
            }
        );
        return alwaysPendinfPromise;
    }
)


export default instance;